<template>
    <div class="container">
        <div class="fixed-box fixed-box-fixed">
          <div class="btn-box flex">
            <div @click="cancelSave">取消</div>
            <div>
              <button @click="saveData">确认保存<template v-if="checkedList.length !== 0">({{checkedList.length}})</template></button>
            </div>
          </div>
        </div>
        <div class="height-49"></div>
        <div class="type-bar flex v-align-c mar-l-15 pad-t-10 pad-b-10 pad-r-15" @click="autoType">
          <div class="width-16 height-11 mar-r-10"></div>
          <div>
            <div class="font-15">自动添加</div>
            <div class="font-12 font-color-9">将所有新/老顾客自动设为{{appInfo.memberShareAlias || '分销商'}}</div>
          </div>
        </div>
        <div class="type-bar flex v-align-c mar-l-15 pad-t-10 pad-b-10 pad-r-15" @click="changeType">
          <div v-if="!typeValue" class="width-16 height-11 mar-r-10"></div>
          <img v-if="fileSpace && typeValue" :src="fileSpace + '/images/icon-radio-5.png'" alt="" class="width-16 height-11 mar-r-10">
          <div class="flex-item">
            <div class="font-15">手动添加<template v-if="(tagCount + checkedList.length) !== 0">({{ tagCount + checkedList.length }})</template></div>
            <div class="font-12 font-color-9">选中的标签组/顾客设为{{appInfo.memberShareAlias || '分销商'}}</div>
          </div>
          <van-icon class="icon-arrow-down" :class="typeValue ? 'icon-arrow-sel':''" name="arrow" size="14px" color="#999999" />
        </div>
        <template v-if="typeValue">
          <div class="tag-bar mar-l-15 pad-t-10 pad-b-10 pad-r-15" @click="tagLayerOpen">
            <p class="font-14">从标签中选择</p>
            <p v-if="checkedTagsTxt" class="font-11 tag-sel">{{ checkedTagsTxt }}</p>
          </div>
          <div class="flex header-box" :class="{'search-icon-none': checkedList.length > 0}">
            <div class="headshop-box">
              <scroll-view class="flex img-row height-35" :enable-flex="true" :scroll-x="true" :scroll-into-view="'headshop-top-' + headshopActive">
                <div v-for="item in checkedList" :key="item" class="img-box" :id="'headshop-top-' + item.memberId" @click="deleteHeadshop(item)">
                  <div v-if="item.checked" >
                    <img v-if="item.avatar && item.checked" class="width-35 height-35" :src="item.avatar" />
                  </div>
                </div>
              </scroll-view>
            </div>
            <div class="search-box">
              <van-search
                v-model="listQuery.nickname"
                placeholder="搜索顾客昵称/手机号"
                clearable="false"
                @search="onSearch"
                placeholder-style='font-size:13px;color:#999999;'>
              </van-search>
            </div>
          </div>        
          <div :class="{'height-101': tabsRow}"></div>
          <div class="customer-title">
            <div>我的顾客<span v-if="!dataNone" class="mar-l-9">({{ listData.length }})</span></div>
          </div>
          <div class="pull-refresh">
              <div class="content-list" v-if="!dataNone">
                  <div class="list-row"
                    v-for="(item, indexSub) in listData" :key="indexSub" @click="checkClick(indexSub, $event)">
                    <van-checkbox :value="item.checked" checked-color="#ffe200"></van-checkbox>
                    <div class="self-cell-box">
                      <div class="self-cell">
                        <img v-if="item.avatar" :src="item.avatar"/>
                        <div class="nickname">{{item.nickname}}</div>
                      </div>
                    </div>
                  </div>
                  <base-line v-if="pullLoad.finished && listQuery.currentPage !== 1"  title='我是有底线滴'></base-line>
              </div>
              <div class="nodata text-align-c" v-else>
                <div class="align-c mar-t-20 font-16 font-color-6">
                  暂无数据~
                </div>
              </div>
          </div>
          <div v-show="tagBoolean" class="tag-layer">
            <div class="tag-layer-box">
              <img v-if="fileSpace" class="width-35 height-35 tag-layer-close"
                   @click="tagLayerClose"
                   :src="fileSpace + '/images/icon-close-6.png'"/>
              <h2>共{{ tagData.length }}个标签</h2>
              <div class="content-list">
                <scroll-view scroll-y="" class="clearfix scroll-box">
                  <template v-if="!tagDataNone">
                    <div class="list-row"
                      v-for="(item, index) in tagData" :key="index" @click="tagClick(item, index)">
                      <van-checkbox :value="item.checked" class="width-per-100" checked-color="#ffe200">
                        <div class="flex v-align-c tag-radio-bar">
                          <div class="font-15 flex-item">{{ item.labelName }}<template v-if="item.customerNum !== 0">({{ item.customerNum }})</template></div>
                          <div>
                            <p class="flex v-align-c">
                              <span class="font-12 font-color-9">消费总额：</span>
                              <span class="font-16 tag-money">￥{{ item.totalPrice }}</span>
                            </p>
                          </div>
                        </div>
                      </van-checkbox>
                    </div>
                  </template>
                  <div class="nodata text-align-c" v-else>
                    <div class="align-c mar-t-20 font-16 font-color-6">
                      暂无数据~
                    </div>
                  </div>
                </scroll-view>
              </div>
              <div class="tag-foot pad-15">
                <button @click="saveTagSel">确认<template v-if="checkedTags.length !== 0">({{ checkedTags.length }})</template></button>
              </div>
            </div>
            <div class="tag-layer-bg" @click="tagLayerClose"></div>
          </div>
        </template>
    </div>
</template>
<script>
import { insertBatch, insertBatchByLabel, paginMyMemberShoppingReport, insertBatchPaging } from '@/api/personal'
import baseLine from '@/components/BaseLine/index'
export default {
  components: { baseLine },
  data() {
    return {
      tagData: [],
      checkedTags: [],
      sureCheckedTags: [],
      checkedTagsTxt: '',
      tagDataNone: false,
      tagBoolean: false,
      typeValue: false,
      value: '',
      dataNone: false,
      showSaveDialog: false,
      showGoSaveDialog: false,
      tabsRow: false, // 用于固定头部
      checkedList: [],
      customerTotal: 0,
      labelGroupId: null,
      resParams: {
        memberId: '',
        labelGroupId: null,
        nickname: ''
      },
      listData: [],
      listQuery: {
        memberId: '',
        buyStatus: '',
        currentPage: 1,
        size: 10,
        nickname: ''
      },
      pullLoad: {
        loading: false,
        finished: false
      },
      currentPage: 1,
      listQueryTag: {
        memberId: '',
        currentPage: 1,
        size: 50
      },
      tagCount: 0,
      saveNum: 0,
      appInfo: {},
      headshopActive: ''
    }
  },
  onLoad() {
    // 重置缓存data里面的数据
    // Object.assign(this.$data, this.$options.data())
  },
  mounted() {
    Object.assign(this.$data, this.$options.data())
    this.appInfo = this.$pt.getStorageSync('appInfo')
    this.$pt.setNavigationBarTitle({
      title: `添加${this.appInfo.memberShareAlias || '分销商'}`
    })
    this.saveNum = 0
    this.typeValue = false
    this.listData = []
    this.currentPage = 1
    this.pullLoad.finished = false
    this.pageInit()
    this.initTag()
  },
  onReachBottom() {
    // 触底刷新
    if (!this.pullLoad.finished) {
      this.pageInit()
    }
  },
  methods: {
    autoType() {
      const that = this
      this.$pt.showModal({
        content: '操作“自动添加"需离开本页面是否确定离开？',
        success(res) {
          if (res.confirm) {
            that.$pt.navigateTo({url: '/pages/home/setting-view/main'})
          }
        }
      })
    },
    changeType() {
      this.typeValue = !this.typeValue
    },
    pageInit() {
      this.listQuery.memberId = this.getCustomerId
      this.listQuery.currentPage = this.currentPage
      paginMyMemberShoppingReport(this.listQuery).then((response) => {
        this.dataNone = false
        if (response.isError) return
        response.data.records.forEach((item, index) => {
          item.checked = false
          this.listData.push(item)
        })
        this.currentPage++
        if (this.listData.length === 0 || this.listData.length >= response.data.total) {
          this.pullLoad.finished = true
        }
        if (this.listData.length === 0) {
          this.dataNone = true
        }
      }).catch(() => {
      })
    },
    initTag() {
      this.listQueryTag.memberId = this.getCustomerId
      insertBatchPaging(this.listQueryTag).then(response => {
        this.tagDataNone = false
        if (response.isError) return
        response.data.records.forEach(item => {
          item.checked = false
          this.tagData.push(item)
        })
        if (this.tagData.length === 0) {
          this.tagDataNone = true
        }
      }).catch({})
    },
    onSearch(e) {
      this.listQuery.nickname = e.mp.detail
      this.currentPage = 1
      this.listData = []
      this.pullLoad.finished = false
      this.pageInit()
    },
    checkClick(index, e) {
      this.listData[index].checked = !this.listData[index].checked
      if (this.listData[index].checked) {
        this.checkedList.push(this.listData[index])
      } else {
        for (let i = 0; i < this.checkedList.length; i++) {
          if (this.checkedList[i].memberId === this.listData[index].memberId) {
            this.checkedList.splice(i, 1)
          }
        }
      }
      const changeData = this.listData[index].checked
      this.$delete(this.listData[index], 'checked')
      this.$set(this.listData[index], 'checked', changeData)
      this.headshopActive = this.listData[index].memberId
      // console.log('选中的数据', this.checkedList)
    },
    deleteHeadshop(item) {
      const index = this.checkedList.findIndex(val => item.memberId === val.memberId)
      const listIndex = this.listData.findIndex(val => item.memberId === val.memberId)
      this.checkedList.splice(index, 1)
      this.$delete(this.listData[listIndex], 'checked')
      this.$set(this.listData[listIndex], 'checked', false)
    },
    tagLayerClose() {
      this.tagBoolean = false
      if (this.checkedTags.length !== 0) {
        this.checkedTags = []
        this.sureCheckedTags.forEach(element => {
          this.checkedTags.push(element)
        })
      }
    },
    tagLayerOpen() {
      this.tagBoolean = true
      this.tagData.forEach(element => {
        element.checked = false
      })
      if (this.sureCheckedTags.length === 0) {
        this.checkedTags = []
      } else {
        this.sureCheckedTags.forEach((itemTag, indexTag) => {
          this.tagData.forEach((itemSure, indexSure) => {
            if (itemTag.labelGroupId === itemSure.labelGroupId) {
              itemSure.checked = true
            }
          })
        })
      }
    },
    tagClick(item, index) {
      this.tagData[index].checked = !this.tagData[index].checked
      if (this.tagData[index].checked) {
        this.checkedTags.push(this.tagData[index])
      } else {
        for (let i = 0; i < this.checkedTags.length; i++) {
          if (this.checkedTags[i].labelGroupId === this.tagData[index].labelGroupId) {
            this.checkedTags.splice(i, 1)
          }
        }
      }
      const changeDataAll = item.checked
      this.$delete(item, 'checked')
      this.$set(item, 'checked', changeDataAll)
      // console.log('选中的数据', this.checkedTags)
    },
    saveTagSel() {
      this.tagCount = 0
      if (this.checkedTags.length !== 0) {
        this.sureCheckedTags = []
        this.checkedTags.forEach(element => {
          this.sureCheckedTags.push(element)
        })
        let sureCheckedTags = []
        this.sureCheckedTags.forEach(item => {
          sureCheckedTags.push(item.labelName)
          if (item.customerNum) {
            this.tagCount += item.customerNum
          }
        })
        this.checkedTagsTxt = sureCheckedTags.join('、')
      } else {
        this.sureCheckedTags = []
        this.checkedTagsTxt = ''
      }
      this.tagBoolean = false
      // this.sureCheckedTags.forEach(element => {
      //   console.log(element.labelName)
      // })
    },
    cancelSave() {
      const that = this
      this.$pt.showModal({
        content: '您将离开本页面,是否保存当前设置?',
        cancelText: '取消',
        confirmText: '保存',
        success(res) {
          if (res.confirm) {
            that.saveEls()
          } else if (res.cancel) {
            that.$pt.navigateBack({delta: -1})
          }
        }
      })
    },
    saveData() {
      const that = this
      this.$pt.showModal({
        content: `是否确认添加当前选择的顾客为${this.appInfo.memberShareAlias || '分销商'}？`,
        success(res) {
          if (res.confirm) {
            that.saveEls()
          }
        }
      })
    },
    saveEls() {
      if (this.checkedList.length !== 0) {
        this.saveNum++
        let customerMemberIds = this.checkedList.map(item => {
          return item.memberId
        })
        let paramsMember = {
          memberId: this.getCustomerId,
          customerMemberIds: customerMemberIds.join(',')
        }
        insertBatch(paramsMember).then(response => {
          if (response.isError) return
          if (this.saveNum === 1) {
            this.$pt.navigateBack({
              delta: 1
            })
          }
        }).catch({})
      }
      if (this.sureCheckedTags.length !== 0) {
        this.saveNum++
        setTimeout(() => {
          let labelGroupIds = this.sureCheckedTags.map(item => {
            return item.labelGroupId
          })
          let paramsLabel = {
            memberId: this.getCustomerId,
            labelGroupIds: labelGroupIds.join(',')
          }
          insertBatchByLabel(paramsLabel).then(response => {
            if (response.isError) return
            this.$pt.navigateBack({
              delta: 1
            })
          }).catch({})
        }, 800)
      }
    }
  }
}
</script>
<style lang="less" scoped>
@color-3: #333333;
@color-w: #ffffff;
@color-y: #f8c400;
@color-9: #999999;
.container{
  background: white;
  min-height: calc(100vh);
  .nodata {
    margin-top: 115px;
    img{
      display: inline-block;
    }
  }
  .tag-layer{
    .tag-layer-box{
      position: fixed;
      left: 0;
      bottom: 0;
      width: 100%;
      z-index: 21;
      background: #fff;
      border-top-left-radius: 1.5em;
      border-top-right-radius: 1.5em;
      overflow: hidden;
      .tag-layer-close{
        position: absolute;
        right: 20px;
        top: 9px;
      }
      h2{
        background: #fff9ce;
        padding: 13px 0;
        font-size: 17px;
        font-weight: bold;
        text-align: center;
        border-top-left-radius: 1.5em;
        border-top-right-radius: 1.5em;
      }
      .content-list{
        padding-left: 15px;
      }
      .scroll-box{
        width: 100%;
        height: 340px;
        .tag-radio-bar{
          width: 303px;
        }
        .list-row{
          height: auto;
          padding: 9px 0 14px 12px;
          &::after{
            content: '';
            position: absolute;
            bottom: 0;
            right: 0;
            width: 100%;
            border-bottom: 1px solid #ededed;
          }
        }
      }
      .tag-money{
        color: #e14949;
      }      
      .tag-foot{
        display: flex;
        justify-content: space-between;
        align-items: center;
        box-sizing: border-box;
        width: 100%;
        border-top: #e2e2e2 1px solid;
        button{
          line-height: normal;
          font-size: 15px;
          padding: 10px 0px;
          border-radius: 10em;
          width: 100%;
          text-align: center;
          background: @color-y;
          color: @color-3;
          &::after{
            border: unset;
          }
        }
      }
    }
    .tag-layer-bg{
      width: 100%;
      height: 100%;
      background: rgba(0, 0, 0, 0.8);
      position: fixed;
      left: 0;
      bottom: 0;
       z-index: 20;
    }
  }
  .type-bar{
    border-bottom: #e5e5e5 1px solid;
  }
  .icon-arrow-down{
    transition: 0.1s;
    transform:rotate(90deg);
    &.icon-arrow-sel{
      transform:rotate(-90deg);
    }
  }
  .radio-box{
    /deep/ .van-radio__icon{
      color: #fff;
    }
    /deep/ .van-radio__icon--checked{
      .van-icon-checked:before{
        content: "\F0C8";
        color: #ffe200;
      }
    }
  }
  .tag-bar{
    border-bottom: #e5e5e5 1px solid;
    padding-left: 55px;
    .tag-sel{
      color: #26a64d;
    }
  }
  .btn-box{
        padding: 0 15px;
        height: 49px;
        font-size: 14px;
        font-weight: bold;
        justify-content: space-between;
        align-items: center;
        // box-shadow: 1px 1px 5px rgba(0, 0, 0, 0.1);
        button{
          background: #ffe200;
          line-height: 1;
          font-size: 14px;
          padding: 6px 10px;
          border-radius: 1em;
          color: #333;
          &::after{
              border: unset;
          }
        }
    }
    .header-box{
        padding: 0 15px;
        justify-content: left;
        align-items: center;
        height: 49px;
        /deep/ .van-search{
            background: white !important;
            padding: 0px;
            // min-width: 80px;
        }
        /deep/ .van-cell--borderless{
            padding: 3px 10px 3px 0px !important;
        }
        /deep/ .van-field__body{
            margin-left: 10px;
        }
        .headshop-box{
            max-width: 240px;
            display: inline-block;
            .img-row{
                overflow-x: scroll;
                .img-box{
                    &:first-child{
                        img{
                            margin-left: 0px;
                        }
                    }
                    img{
                        // flex-basis: 35px;
                        flex-shrink: 0;
                        width: 35px;
                        height: 35px;
                        border-radius: 50%;
                        margin-left: 10px;
                    }
                }
            }
        }
        .search-box{
            display: inline-block;
            width: 100%;
        }
    }
}
.fixed-box{
  top: 0;
  left: 0;
  height: 49px;
  width: 100%;
  background: white;
  z-index: 99;    
}
.fixed-box-fixed{
    position: fixed;
    top: 0;
    left: 0;
    box-shadow: 0px 2px 6px rgba(0, 0, 0, 0.1);
}
.customer-title{
    font-size: 13px;
    padding: 0 15px;
    height: 35px;
    line-height: 35px;
    background: #fafafa;
}
.content-list{
    .list-row{
        height: 50px;
        position: relative;
        display: flex;
        justify-content: left;
        align-items: center;
        padding: 0 15px;
        &:last-child{
          &::after{
            content: '';
            display: none;
          }
        }
        &::after{
            content: '';
            position: absolute;
            bottom: 0;
            right: 0;
            width: calc(100% - 95px);
            border-bottom: 1px solid #ededed;
        }
        // /deep/ .van-checkbox{
        //     .van-checkbox__icon-wrap{
        //         padding-left: 15px;
        //     }
        //     .van-checkbox__label{
        //         width: 88%;
        //     }
        // }
        // /deep/ .van-radio__label{
        //     margin-left: 13px;
        // }
        .self-cell-box{
            width: 100%;
            .self-cell{
                margin-left: 13px;
                margin-top: 5px;
                height: 45px;
                display: flex;
                justify-content: left;
                align-items: center;
                img{
                    width: 35px;
                    height: 35px;
                    border-radius: 50%;
                    margin-right: 12px;
                }
                .nickname{
                    font-size: 15px;
                    color: #333333;
                    width: calc(100% - 47px);
                    height: 44px;
                    line-height: 44px;
                    // border-bottom: 1px solid #ededed;
                }
            }
        }
    }
}
.show-dialog{
  /deep/ .van-popup{
    top: 205px;
  }
  /deep/ .van-dialog__header{
    font-size: 18px;
    color: #333333;
    font-weight: bold;
    line-height: 1.3;
    padding-top: 36px;
    padding-bottom: 31px;
    width: 235px;
    margin: 0 auto;
  }
}
.search-icon-none{
  /deep/ .van-icon-search {
    &::before{
      content: unset;
    }
  }
}
</style>
